
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = 'random_name'
now = timestamp = Date.parse(new Date()) / 1000; 

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        serverUrl = './OSS/OSSHandler.ashx'
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};

function check_object_radio() {
    //var tt = document.getElementsByName('myradio');
    //for (var i = 0; i < tt.length ; i++ )
    //{
    //    if(tt[i].checked)
    //    {
    //        g_object_name_type = tt[i].value;
    //        break;
    //    }
    //}
    g_object_name_type == 'random_name';
}

function get_signature()
{
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}

function set_upload_param(filename, ret) {
    if (ret == false) {
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        //'name': filename,
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        'callback': callbackbody,
        'signature': signature,
    };
    return new_multipart_params;
    //up.setOption({
    //    'url': host,
    //    'multipart_params': new_multipart_params
    //});

    //up.start();
}

$("#f_upload").fileinput({
    theme: "explorer", //主题
    language: 'zh',
    enctype: 'multipart/form-data',
    uploadUrl: "https://kezhang.oss-cn-qingdao.aliyuncs.com",// 上传请求路径
    allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg', 'pdf'],//允许上传的文件后缀      
    uploadAsync: true, //是否允许异步上传
    showUpload: true,//是否显示上传按钮
    showCaption: true,//是否显示容器
    dropZoneEnabled: true,//是否显示拖拽区域 
    removeFromPreviewOnError: true,//是否移除校验文件失败的文件
    uploadExtraData: function (previewId, index) {   //额外参数 返回json数组  
        var param = {};
        //向后台传递type,nameStr作为额外参数
        if (index>-1) {//判断是否有文件
            param= set_upload_param(this.filenames[index], false);//重点是这个
        }
        return param;
    },
    layoutTemplates: {    //取消上传按钮
        actionUpload: '',
    },
    showPreview: true,      //显示预览   
    minFileCount: 1,   //最低文件数量
    maxFileCount: 5,   //最多文件数量
    maxFileSize: 9000,  //允许文件上传大小
    overwriteInitial: true,
    previewFileIcon: '<i class="fa fa-file"></i>',
    initialPreviewAsData: true, // defaults markup  
    preferIconicPreview: false, // 是否优先显示图标  false 即优先显示图片
    previewFileIconSettings: { // configure your icon file extensions
        'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',
        'jpg': '<i class="fa fa-file-photo-o text-danger"></i>',
        'gif': '<i class="fa fa-file-photo-o text-muted"></i>',
        'png': '<i class="fa fa-file-photo-o text-primary"></i>',
        'jpeg': '<i class="fa fa-file-photo-o text-primary"></i>'
    },
    layoutTemplates: {
        //actionDelete:'', //去除上传预览的缩略图中的删除图标
        actionUpload: '',//去除上传预览缩略图中的上传图片；
        //actionZoom:''   //去除上传预览缩略图中的查看详情预览的缩略图标。
    },
});

$("#f_upload").fileinput();
